package com.action;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.pojo.*;
import com.service.*;
import com.util.StringUtil;
import com.util.ValidateHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Author: T-bao
 * @Date: 2021-3-26 14:41
 * @Description:
 */
@RestController
@RequestMapping("/qiye")
public class QiyeAction {

    @Autowired
    private QiyeService qiyeService;
//    @Autowired
//    private AdminRoleService adminRoleService;

    @Autowired
    private StaffHistoryService staffHistoryService ;

    @Value("${upload.dir}")
    private String upload;

    @Value("${upload.tmp.dir}")
    private String tmp;

//    @Autowired
//    private SshCopyFileService sshCopyFileService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private CardService cardService;

//    @Autowired
//    private StaffQiyeChangeRecordService staffQiyeChangeRecordService;

    /**
     * @param qyname 企业名称
     * @param page   页数
     * @param limit  每页条数
     * @return 查询未审核企业
     */
    @RequestMapping("/shenheqiye")
    public ResponseBean shenheqiye(String qyname, int page, int limit) {
        if (qyname == "") {
            qyname = null;
        }

        IPage iPage = qiyeService.shenheQiye(qyname, page, limit);
//        int count = qiyeService.shenhecount(qyname);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }

    /**
     * 查找状态为启用已审核的企业
     *
     * @return
     */
    @RequestMapping("/selectqiyestatus")
    public ResponseBean selectWuyeStatus() {
        List<Qiye> qiye = qiyeService.QiyeStatus();
        return new ResponseBean(0, 1, "查找启用企业", qiye);
    }

    /**
     * @param qiye
     * @return 修改企业
     */
    @RequestMapping("/updateqiye")
    public ResponseBean updateQiye(@RequestBody Qiye qiye, int denglu, HttpServletRequest request) {

        String qyname = qiye.getQyname();
        String id = qiye.getId();
        //System.out.println("企业名称："+qyname+" 企业id："+id+" wyID："+qiye.getWyID());

        int i = qiyeService.countName(qyname);
        int m = qiyeService.countNameID(qyname, id);

        if (i >= 1 && m == 0) {
            return new ResponseBean(2, 1, "重复", "企业名称重复");
        } else {
//            Wuye wuye = (Wuye) request.getSession().getAttribute("wuye");
            if (denglu==0) {
                qiye.setShstatus(0);
            }
            Qiye qy = qiyeService.selectID(qiye.getId());
            qiye.setStatus(qy.getStatus());
            if (StringUtil.isNotNull(qiye.getQycode())) {
                int c1 = qiyeService.selectQyCode(qiye.getQycode(),null);
                int c2 = qiyeService.selectQyCode(qiye.getQycode(),id);
                if (c1 >= 1 && c2 == 0) {
                    return new ResponseBean(5, 1, "企业编码已存在");
                }
            }

            if (qiyeService.updateById(qiye)) {
                if (StringUtil.isNotNull(qy.getLogo()) && qy.getLogo().equals(qiye.getLogo()) == false) {
                    FileUtil.copy(tmp + qiye.getLogo(), upload, true) ;
//                    sshCopyFileService.copy(upload + qiye.getLogo());
                    //tmp复制图片到upload
//                    String srcPathStr = tmp + qiye.getLogo(); //源文件地址
//                    String desPathStr = upload; //目标文件地址
//                    CopyFile.copy(srcPathStr, desPathStr);
                }
                return new ResponseBean(0, 1, "修改成功", "修改成功");
            } else {
                return new ResponseBean(1, 1, "修改失败", "修改失败");
            }
        }
    }

    /**
     * 特行办新增企业
     * @param qiye 企业类
     * @return
     */
    @RequestMapping("/addqiye")
    public ResponseBean jtAddWuye(@RequestBody Qiye qiye, HttpServletRequest request) {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
//        List<String> list = adminRoleService.shifouGuanliyuan(userinfo.getId());
//        for (int X = 0; X < list.size(); X++) {
//            //管理员新增
//            if (list.get(X) == "管理员" || list.get(X).equals("管理员")) {
//                qiye.setShstatus(1);
//                return addQiye(qiye);
//            }
//        }
//        //录入员新增
//        qiye.setShstatus(0);
        qiye.setShstatus(1);
        if (null != admin) {
            qiye.setOperUser(admin.getId());
        }
        ResponseBean bean = addQiye(qiye);
        return bean;
    }

    /**
     * 新增企业
     * @param qiye
     * @return
     */
    private ResponseBean addQiye(Qiye qiye) {
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        qiye.setCreateTime(new Date());
        String qyname = qiye.getQyname();
        int i = qiyeService.countName(qyname);

        if (StringUtil.isNotNull(qiye.getQycode())) {
            int c = qiyeService.selectQyCode(qiye.getQycode(),null);
            if (c != 0) {
                return new ResponseBean(5, 1, "企业编码已存在");
            }
        }
        if (i == 0) {
            if (qiyeService.save(qiye)) {
                if (StringUtil.isNotNull(qiye.getLogo())) {
                    FileUtil.copy(tmp + qiye.getLogo(), upload, true) ;
//                    sshCopyFileService.copy(upload + qiye.getLogo());
                    //tmp复制图片到upload
//                    String srcPathStr = tmp + qiye.getLogo(); //源文件地址
//                    String desPathStr = upload; //目标文件地址
//
//                    CopyFile.copy(srcPathStr, desPathStr);
                }
                return new ResponseBean(0, 1, "成功", "新增成功");
            } else {
                return new ResponseBean(1, 1, "失败", "新增失败");
            }
        } else {
            return new ResponseBean(2, 1, "该企业已存在", "该企业已存在");
        }
    }

    /**
     * 物业登录新增企业
     * @param qiye
     * @param request
     * @return
     */
    @RequestMapping("/wy_addqiye")
    public ResponseBean wyAddWuye(@RequestBody Qiye qiye, HttpServletRequest request) {
        Wuye wuye = (Wuye) request.getSession().getAttribute("wuye");
        qiye.setShstatus(0);
        if (null != wuye) {
            qiye.setWyID(wuye.getId());
            qiye.setOperUser(wuye.getId());
        }
        ResponseBean bean = addQiye(qiye);
        return bean;
    }

    /**
     * @param qyname 企业名称
     * @param page   页数
     * @param limit  每页条数
     * @param wyid   物业编号
     * @return 查询企业
     */
    @RequestMapping("/selectqiye")
    public ResponseBean selectQiye(String qyname, int page, int limit, @RequestParam(required = false) String wyid, Integer status) {
        if (StringUtil.isNull(qyname)) {
            qyname = null;
        }
        if (StringUtil.isNull(wyid)) {
            wyid = null;
        }
        if (page == 1) {
            page = 0;
        } else {
            page = (page * limit) - limit;
        }
        int count = qiyeService.count(qyname, wyid, status);
        return new ResponseBean(0, count, "成功", qiyeService.selectQiye(qyname, page, limit, wyid, status));
    }

    /**
     * @param qyname 企业名称
     * @param page   页数
     * @param limit  每页条数
     * @return 物业登录查询企业
     */
    @RequestMapping("/wy_selectqiye")
    public ResponseBean wySelectQiye(String qyname, int page, int limit, HttpServletRequest request, Integer status) {
        Wuye wuye = (Wuye) request.getSession().getAttribute("wuye");
        if (qyname == "") {
            qyname = null;
        }
        if (page == 1) {
            page = 0;
        } else {
            page = (page * limit) - limit;
        }
        int count = qiyeService.count(qyname, wuye.getId(), status);
        return new ResponseBean(0, count, "成功", qiyeService.wySelectQiye(qyname, page, limit, wuye.getId(), status));
    }

    /**
     * 物业登录查询启用已审核企业
     * @param request
     * @return
     */
    @RequestMapping("wy_selectqiyestatus")
    public ResponseBean wySelectqiyestatus(HttpServletRequest request) {
        Wuye wuye = (Wuye) request.getSession().getAttribute("wuye");
        List<Qiye> qiye = qiyeService.wyQiyeStatus(wuye.getId());
        return new ResponseBean(0, 1, "查找启用企业", qiye);
    }

    /**
     * @return 查询物业包含企业（管理员）
     */
    @RequestMapping("/selectqiyes")
    public ResponseBean selectQiyes(String wuye) {
        //System.out.println(qiyeService.selectQiye(qyname,page,limit));
        return new ResponseBean(200, 0, "成功", qiyeService.selectQiyes(wuye));
    }

    /**
     * 查询物业包含企业（录入员）
     */
    @RequestMapping("/selectLuQiyes")
    public ResponseBean selectLuQiyes(String wuye) {
        return new ResponseBean(200, 0, "成功", qiyeService.selectQiyes(wuye));
    }

    /**
     * 删除企业
     * @param id 企业ID
     * @return
     */
    @RequestMapping("/delqiye")
    public ResponseBean delqiye(String id) {
        if (ValidateHelper.isEmptyString(id)) {
            return new ResponseBean(1, "ID为空", "ID为空");
        }
        if (qiyeService.removeById(id)) {
            return new ResponseBean(0, 1, "成功", "删除成功");
        } else {
            return new ResponseBean(1, 1, "失败", "删除失败");
        }
    }

    /**
     * 物业，管理员修改企业状态
     */
    @RequestMapping("/upStatus")
    @ResponseBody
    public ResponseBean changeStatus(String id, int status, int denglu, String remark, HttpServletRequest request) {

        Qiye qiye = new Qiye();
        qiye.setId(id);
        qiye.setStatus(status);

        if (denglu==0) {
            qiye.setShstatus(0);
            return new ResponseBean(0, 1, "", qiyeService.updateById(qiye));
        }else{
            // 删除
            if (status == 2) {
                List<Staff> staffList = staffService.getStaffByQyId(id);
                if (ValidateHelper.isNotEmptyCollection(staffList)) {
                    for (Staff staff : staffList) {
                        StaffHistory staffHistory = new StaffHistory();
                        BeanUtils.copyProperties(staff, staffHistory);
                        staffHistory.setCreatetime(new Date());
                        staffHistory.setOperType(2);
                        staffHistory.setRemark(remark);

                        //写员工企业变更记录
//                        staffQiyeChangeRecordService.saveStaffQyChangeRecord(staff.getQyID(), "",staff.getId());

                        staffService.removeById(staff.getId());
                        staffHistoryService.save(staffHistory);
                    }
                }
            }
            qiye.setRemark(remark);
            return new ResponseBean(0, 1, "", qiyeService.updateById(qiye));
        }
    }

    /**
     * 修改企业审核状态
     */
    @RequestMapping("/hfQiye")
    @ResponseBody
    public ResponseBean hfQiye(String id) {
        Qiye qiye = qiyeService.getById(id);
        if (null != qiye) {
            List<StaffHistory> staffHistoryList = staffHistoryService.getStaffHistoryByQyId(id);
            if (ValidateHelper.isNotEmptyCollection(staffHistoryList)) {
                for (StaffHistory staffHistory : staffHistoryList) {
                    boolean existFlag = false;
                    Staff staffDb = staffService.getById(staffHistory.getId());
                    Staff staff = new Staff();
                    // 判断恢复员工的ID在staff表是否存在，存在则重新生成ID，不存在则用原来老的ID
                    if (staffDb == null) {
                        BeanUtils.copyProperties(staffHistory, staff);
                        existFlag = true;
                    } else {
                        BeanUtils.copyProperties(staffHistory, staff, "id");
                        existFlag = false;
                    }

                    if (staffService.save(staff)) {
                        if (staffHistoryService.removeById(staffHistory.getId())) {
                            if (!existFlag) {
                                // 判断恢复员工是否有卡号，有卡号则将卡表绑定的staff_id 重新绑定为新的
                                if (ValidateHelper.isNotEmptyString(staff.getCardNo())) {
                                    Card card = cardService.getCardByCardNo(staff.getCardNo());
                                    card.setStaffId(staff.getId());
                                    cardService.updateById(card);
                                }
                            }
                        }
                    }
                }
            }
        }
        qiye.setStatus(1);
        qiyeService.updateById(qiye);
        return ResponseBean.ok("恢复成功");
    }


   /**
    * 修改企业审核状态
    */
    @RequestMapping("/updateshqiye")
    @ResponseBody
    public String updateshqiye(String id) {
        // 修改状态，返回修改后的状态
        Qiye gnaddress = qiyeService.upshStatus(id);
        if (gnaddress != null)
           return gnaddress.getShstatus() + "";
       return "";
   }

    /**
     * 根据企业ID查询企业
     * 查企业到期时间
     */
    @RequestMapping("/selectQiyeID")
    public ResponseBean selectQiyeID(String id){
        return new ResponseBean(200,1,"",qiyeService.selectID(id));
    }

    /**
     * 查询已到期企业 分页
     */
    @RequestMapping("/yidaoqiQiye")
    public ResponseBean selectYidaoqi(String qyname, @RequestParam(defaultValue = "1") Integer page , @RequestParam(defaultValue = "10") Integer limit){
        if(StringUtil.isNull(qyname)) {
            qyname = null ;
        }
        IPage iPage = qiyeService.selectYidaoqi(qyname,page,limit);
        return new ResponseBean(0,iPage.getTotal(),"",iPage.getRecords());
    }

    /**
     * 查询已到期企业数量
     */
    @RequestMapping("/yidaoqiQiyeCount")
    public ResponseBean selectYidaoqiCount(){
        return new ResponseBean(200,1,"",qiyeService.selectYidaoqiCount());
    }

    /**
     * 查询即将到期企业 分页
     */
    @RequestMapping("/jiJiangDaoQiQiye")
    public ResponseBean jiJiangDaoQiQiye(String qyname, @RequestParam(defaultValue = "1") Integer page , @RequestParam(defaultValue = "10") Integer limit){
        if(StringUtil.isNull(qyname)) {
            qyname = null ;
        }
        IPage<Qiye> iPage = qiyeService.selectJiJiangDaoQi(qyname,page,limit);
        return new ResponseBean(0,iPage.getTotal(),"",iPage.getRecords());
    }

    /**
     * 查询所有企业
     */
    @RequestMapping("/getAllQiye")
    public ResponseBean getAllQiye(String wuye){
        return new ResponseBean(200,1,"",qiyeService.getAllQiye(wuye));
    }
}
